package lbs.locationretreival;

import java.io.File;
import java.util.List;


import android.app.Activity;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class DataLoggerActivity extends ListActivity {

	TextView mainText;
	WifiManager mainWifi;
	WifiReceiver receiverWifi;
	List<ScanResult> wifiList;
	SQLiteDatabase database;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.datalogger);
       
        
	  //mainText = (TextView) findViewById(R.id.mainText);
      mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
      database = createDB();
      
      receiverWifi = new WifiReceiver();
      registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
      mainWifi.startScan();
      //mainText.setText("\nStarting Scan...\n");
      
      String[] srcfields = new String[] {
    		  "_id","bssid", "ssid",
    		  "capabilities","level",
			"frequency","lat","lon",
			"alt","timestamp"
      };
      
      int[] dstfields = new int[] {
    		 R.id.frow,R.id.fbssid,R.id.fssid,    	     
    		 R.id.fcapabilities,R.id.flevel,
    		 R.id.ffrequency,R.id.flat,
    		 R.id.flon,R.id.falt,R.id.ftimestamp 
       }; 

      Cursor cur = database.query("wifiap", srcfields,null,null,null,null,null);
      startManagingCursor(cur);
          
      SimpleCursorAdapter adapter = new SimpleCursorAdapter(
  			this,
  			R.layout.datalogger_row,
  			cur,
  			srcfields,
  	        dstfields);
          
          setListAdapter(adapter);
	}
	

	private SQLiteDatabase createDB()
	{
		String path = null;
		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
			File file = new File(getExternalFilesDir(null), "wifiappdb.db3");
			path = file.getAbsolutePath();
		}
		if (path == null) {
			Log.d("Dbpath-error", path);
			return null;
		}
		Log.d("Dbpath", path);
		
		SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);
		if (db != null) {
			database.execSQL("create table if not exists wifiap (bssid text primary key, ssid text, capabilities text, level integer, frequency integer, lat real, lon real, alt real, timestamp integer)");
			database.execSQL("create index if not exists wifiap_latlon_idx on wifiap(lat, lon)");
		}
		return db;
	}
	
	private void updateDB(ScanResult result, double lat, double lon, double alt)
	{
			Cursor cursor = null;
			boolean toadd = false;
			boolean toupdate = false;
			boolean toupdate_coords = false;
			boolean toupdate_values = false;
			try
			{
				cursor = database.query("wifiap", new String[] {
						"level", "ssid",
						"capabilities", "frequency",
						"timestamp" }, "bssid = ?",
						new String[] { result.BSSID }, null, null, null);
				
				if (!cursor.moveToFirst())
					toadd = true;
				else
				{
					toupdate_values = !cursor.getString(1).equals(result.SSID)
							|| !cursor.getString(2).equals(result.capabilities) || cursor.getInt(3) != result.frequency;
					toupdate_coords = result.level > cursor.getInt(0);
					toupdate = toupdate_values || toupdate_coords;
				}
			}
			finally
			{
				
				if (cursor != null && cursor.isClosed()) 
					cursor.close();
			}

			if (toadd)
			{
				ContentValues values = new ContentValues();
				values.put("bssid", result.BSSID);
				values.put("ssid", result.SSID);
				values.put("capabilities", result.capabilities);
				values.put("frequency", result.frequency);
				values.put("level", result.level);
				values.put("lat", lat);
				values.put("lon" , lon);
				values.put("alt", alt);
				values.put("timestamp", System.currentTimeMillis());

				database.insert("wifi_ap", null, values);
			}
			else if (toupdate)
			{
				ContentValues values = new ContentValues();

				if (toupdate_values)
				{
					values.put("ssid", result.SSID);
					values.put("capabilities", result.capabilities);
					values.put("frequency", result.frequency);
				}

				if (toupdate_coords)
				{
					values.put("lat", lat);
					values.put("lon", lon);
					values.put("alt", alt);
					values.put("level", result.level);
				}

				values.put("timestamp", System.currentTimeMillis());
				database.update("wifiap", values, "bssid = ?",
						new String[] { result.BSSID });
			}

		
	}
		
	class WifiReceiver extends BroadcastReceiver {
		public void onReceive(Context c, Intent intent) {

			wifiList = mainWifi.getScanResults();
	        for(int i = 0; i < wifiList.size(); i++){
	        	updateDB(wifiList.get(i),0.0,0.0,0.0);
	        }
		}
	}
	
	
}
